package org.luckyjourney.util;

/**
 * @author 飒飒
 * @ClassName HttpUtil
 * @description: TODO
 * @date 2024年03月12日
 * @version: 1.0
 */

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
public class HttpUtil {

    /**
     * http post 请求
     *
     * @param url 请求地址
     * @param json 主报文（json字符串格式）
     * @param userId 报文头参数
     * @return
     */
    public static String sendHttpsRequest(String url, String json, String userId) {
        String result = "";
        DefaultHttpClient httpclient = new DefaultHttpClient();

        try {
            HttpPost hPost = new HttpPost(url);
            hPost.setHeader("Content-Type", "application/json; charset=gbk");
            hPost.setHeader("Accept", "application/json");
            hPost.setHeader("userId", userId);
            StringEntity strentity = new StringEntity(json, "UTF-8"); // or "gbk"
            hPost.setEntity(strentity);
            HttpResponse response = httpclient.execute(hPost);
            response.setHeader("Content-type", "textml;charset=UTF-8");
            result = EntityUtils.toString(response.getEntity(), "iso-8859-1"); // or "UTF-8"
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("异常：" + e.getMessage());
        } finally {
            httpclient.getConnectionManager().shutdown();
        }

        return result;
    }

    /**
     * http get 请求
     *
     * @param Url 请求地址
     * @param param 请求参数 （key=value&key=value 格式）
     * @return
     */
    public static String HttpsGetJson(String Url,String token, String param,String RequestMethod) {
        String message = "";
        try {

            String urlNameString = Url + "?" + param;
            URL urlGet = new URL(urlNameString);
            HttpURLConnection http = (HttpURLConnection) urlGet
                    .openConnection();
            http.setRequestMethod(RequestMethod);
            http.setRequestProperty("Content-Type",
                    "multipart/form-data");
            http.setRequestProperty("token",token);
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
            System.setProperty("sun.net.client.defaultReadTimeout", "30000");
            http.connect();
            InputStream is = http.getInputStream();
            //延时执行
            Thread.sleep(100);
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            message = new String(jsonBytes, "UTF-8");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return message;
    }

    /**
     * http post 请求
     *
     * @param url 请求地址
     * @param xml 请求报文（xml格式字符串）
     * @return
     */
    public static String doHttpsPostXml(String url,String token, String xml,String RequestMethod) {
        String returnStr = "";
        HttpURLConnection conn = null;
        InputStream fis = null;
        String urlparams = xml;
        try {
            URL httpurl = new URL(url);
            conn = (HttpURLConnection) httpurl.openConnection();

            conn.setDoOutput(true);
            conn.setRequestMethod(RequestMethod);
            conn.setRequestProperty("Content-Type",
                    "application/json");
            conn.setConnectTimeout(600000);
            conn.setReadTimeout(600000);
            conn.setRequestProperty("token",token);
//            connection.setRequestProperty("token", token);

            OutputStream op = conn.getOutputStream();
            op.write(urlparams.getBytes());

            op.flush();
            op.close();

            if (conn.getResponseCode() == 200) {
                fis = conn.getInputStream();
                returnStr = StreamToStr(fis, "utf-8");
            }

        } catch (Exception e) {
            returnStr = e.getMessage();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                returnStr = e.getMessage();
            }
            conn.disconnect();
        }
        return returnStr;
    }



    public static String doPost(String url, String requestXml) {
        CloseableHttpClient httpClient;
        CloseableHttpResponse httpResponse;
        // 创建httpClient连接对象
        httpClient = HttpClients.createDefault();
        // 创建post请求连接对象
        HttpPost httpPost = new HttpPost(url);
        // 创建连接请求对象,并设置连接参数
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(15000)   // 连接服务区主机超时时间
                .setConnectionRequestTimeout(60000) // 连接请求超时时间
                .setSocketTimeout(60000).build(); // 设置读取响应数据超时时间
        // 为httppost请求设置参数
        httpPost.setConfig(requestConfig);
        // 将上传参数放到entity属性中
//        httpPost.setEntity(new StringEntity(requestXml, "UTF-8"));
        // 添加头信息
        httpPost.addHeader("Content-type", "text/event-stream");
        String result = "";
        try {
            // 发送请求
            httpResponse = httpClient.execute(httpPost);
            // 从相应对象中获取返回内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }



    public static String StreamToStr(InputStream in, String encoding) {

        StringBuffer out = new StringBuffer();
        try {

            char[] b = new char[1024];
            InputStreamReader inread = new InputStreamReader(in, encoding);

            for (int n; (n = inread.read(b)) != -1;) {
                String line = new String(b, 0, n);
                out.append(line);
            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return out.toString();
    }

    public static String post(String uri, List<NameValuePair> nvps)
            throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));

            System.out.println("请求摘要如下：");
            System.out.println("请求方法：" + httpPost.getMethod());
            System.out.println("请求uri：" + httpPost.getURI());
            System.out.println("Http协议版本号：" + httpPost.getProtocolVersion());
            System.out.println("请求详细如下：");
            System.out.println(EntityUtils.toString(httpPost.getEntity()));
            System.out.println(httpPost.getRequestLine());

            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                HttpEntity entity = response.getEntity();
                String content = EntityUtils.toString(response.getEntity(),
                        "utf-8");
                EntityUtils.consume(entity);
                return content;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

}


